<template>
  <el-select v-model="itemValue" placeholder="Select">
    <el-option v-for="item in options" :key="item.value" v-bind="item" />
    <template #footer>
      <el-button v-if="!isAdding" text bg size="small" @click="onAddOption"> 添加一个项 </el-button>
      <template v-else>
        <el-input v-model="optionName" class="option-input" placeholder="input option name" size="small" />
        <el-button type="primary" size="small" @click="onConfirm"> 确定 </el-button>
        <el-button size="small" @click="clear">取消</el-button>
      </template>
    </template>
  </el-select>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';

const isAdding = ref(false)
const optionName = ref('')

interface Props {
  dataForm: ObjectAny // 绑定对象
  options: any[] // 组件配置
}
const props = withDefaults(defineProps<Props>(), {})
const emit = defineEmits(['change', 'addOption'])


const itemValue = computed({
  get() {
    return props.dataForm['demo8']
  },
  set(value) {
    emit('change', 'demo8', value)
  }
})

const onAddOption = () => {
  isAdding.value = true
}

const onConfirm = () => {
  if (optionName.value) {
    // cities.value.push({
    //   label: optionName.value,
    //   value: optionName.value,
    // })
    emit('addOption', optionName.value)
    clear()
  }
}

const clear = () => {
  optionName.value = ''
  isAdding.value = false
}
</script>

<style lang="scss" scoped>
.option-input {
  width: 100%;
  margin-bottom: 8px;
}
</style>
